#!/usr/bin/python
#
#

from time import sleep

import sys

PYTHON_VERSION = sys.version_info


import telnetlib


class dlinkTelnet(telnetlib.Telnet):
	def __init__(self, host=None, port=0, user=None, password=None,
                    timeout=30):
        if PYTHON_VERSION < (2, 6):
    		telnetlib.Telnet.__init__(self, host, port)
        else:
    		telnetlib.Telnet.__init__(self, host, port, timeout)
        self.vendor = 'dlink'
		self.__enable = None
		self.command = None
		self.__user = user
		self.__password = password
		self.Login()

	def setUser(self, user):
		self.__user = user

	def setPassword(self, password):
		self.__password = password

	def setEnable(self, enable):
		self.__enable = enable

	def Login(self):
		if self.__user and self.__password:
			#
			#print self.read_until('UserName:', 3)
			#print ' ---------------------- Got userprompt'
			sleep(2)
			self.write('%s\n' % self.__user)
			#print self.read_until('PassWord:', 3)
			#print ' ---------------------- Got passprompt'
			sleep(2)
			self.write('%s\n' % self.__password)

			# print self.read_until('#')
			print self.expect(['#'], 3)
			print ' ---------------------- Got cmdprompt'
			sleep(2)
			## back to unpriv. mode:
			#self.write('disable\n')
			#self.read_until('> ')

			#
		else:
			raise ValueError

	def Enable(self, enable=None):
		pass
		#if enable:
		#	 self.__enable = enable
		#if self.__enable:
		#	 self.write('enable\n')
		#	 self.read_until("Password:")
		#	 self.write('%s\n' % self.__enable)
		#	 self.expect(['#'])
		#else:
		#	 raise ValueError

	def setCommand(self, command):
		self.__command = command

	def Execute(self, command):
		self.write('%s\n' % command)
		return self.expect(['#'], 3)
		# sleep(7)

